import { getAnimaLocalStatus } from '../../components/aaanewApp/global/anima/animation';
import { reorderbyWeight } from '../../components/aaanewApp/global/digitalFunc/data2DeepChange/reorderbyWeight';

import {
  domTree,
  endsTimeAnimation,
  //   removeClass,
  settimeNth,
} from '../../components/aaanewApp/global/global';

import { getTargetEl } from '../../components/aaanewApp/global/element/getTargetEl';
import {
  ShortWay,
  TwoWayBind,
} from '../../components/aaanewApp/global/algo/shortestWay/lookingforShortestWayOnArray';
import { longestChildArr_n2 } from '../../components/aaanewApp/global/digitalFunc/longestChildIncreaseArr/longestIncreaseArr2';

//每个 动画的延迟时间
let delayT = 100;

let totalComps = {
  data: ['vasl', 'ssss', 'a367', 'e9325'],
  ssss: { weight: 63 },
  vasl: { weight: 958 },
  a367: { weight: 43 },
  e9325: { weight: 16 },
};

// let waitComps = { data: ['ssss'], ssss: { display: false } };

//作用 根元素 bunt_getme
let containerKey = '.bunt_getme';

let selectedComps = { data: [] };

let lastSelectedCompsDir = { data: [] };

//内部 关键 分割线
let splitPart = '_';

/**
 * 添加 组件
 * @param {Event} event 按钮 点击 事件
 * @returns
 */
function addCompsH(event) {
  let element = event.target;
  let searchFather = getTargetEl(element, containerKey);
  if (!searchFather['done']) {
    return;
  }
  element = searchFather['value'];
  //   console.log(element);
  let value = element.getAttribute('value');

  let addedB = setSelectedComps(value);
  if (addedB) {
    renderSelectedComps(value);
  }
}

/**
 * 移除 组件
 * @param {Event} event 按钮 点击 事件
 * @returns
 */
function removeCompsH(event) {
  let element = event.target;
  let searchFather = getTargetEl(element, containerKey);
  if (!searchFather['done']) {
    return;
  }
  element = searchFather['value'];
  //   console.log(element);
  let value = element.getAttribute('value');

  removeSelectedComps(value);

  let computedEl = window.getComputedStyle(element);
  //   console.log(computedEl);
  element.style = `--clientHeight:${computedEl.height};`;

  let delayDropTime = endsTimeAnimation(element, 'removeCompsAnimation');
  //   console.log(delayDropTime);

  settimeNth([0, delayDropTime], () => {
    element.remove();
    // waitComps[value]['display'] = true;
    // let waitCompEl = document.getElementById(`wait_${value}`);
    // waitCompEl.style = `--clientHeight:0px;`;

    // removeClass(waitCompEl, 'disnone');
    // let displayTime = endsTimeAnimation(waitCompEl, 'rebackCompsAnimation');
    // settimeNth([0, displayTime], () => {
    //   console.log('移除 waitComps 的 Style', waitCompEl);
    //   waitCompEl.removeAttribute('style');
    // });
  });
}

/**
 * 向 选中组件数组 selectedComps 中 添加 默认 信息
 * @param {Array} selectedArr 默认选中的 数组
 */
function setStartSelectedComps(selectedArr) {
  let currentEl = document.getElementById('active_comps');
  for (let i = 0; i < selectedArr.length; i++) {
    let addedB = setSelectedComps(selectedArr[i]);
    if (addedB && !checkElementArrive(selectedArr[i])) {
      if (getAnimaLocalStatus(currentEl)) {
        // console.log('1');
        renderSelectedComps(selectedArr[i]);
      } else {
        settimeNth([delayT * i], () => {
          //   console.log('1*', i);
          renderSelectedComps(selectedArr[i]);
        });
      }
    }
  }
  //   console.log(selectedComps);
}

/**
 * 向 选中组件数组 selectedComps 中 尝试添加 信息
 * @param {String} compId 添加 选中的组件
 * @returns
 */
function setSelectedComps(compId) {
  if (totalComps['data'].indexOf(compId) == -1) {
    return false;
  }
  if (totalComps[compId] == undefined) {
    return false;
  }
  //不重复 添加
  if (selectedComps['data'].indexOf(compId) > -1) {
    return false;
  }
  selectedComps['data'].push(compId);
  selectedComps[compId] = { weight: totalComps[compId]['weight'] };

  return true;
}

function removeSelectedComps(compId) {
  let index = selectedComps['data'].indexOf(compId);
  if (index > -1) {
    let key = selectedComps['data'].splice(index, 1);
    // console.log(selectedComps, key, compId);
    delete selectedComps[key];
    return true;
  }
  return false;
}

/**
 * 根据 权重进行 重排序
 */
function reorderComps() {
  //   console.log(selectedComps['data'], selectedComps);

  /**
   * 记录 每一次 重组 信息 可能 提供 reback 操作
   */
  let timeKey = 'pre_' + lastSelectedCompsDir['data'].length;
  lastSelectedCompsDir['data'].push(timeKey);
  lastSelectedCompsDir[timeKey] = new Array(...selectedComps['data']);

  /**
   * 升序 数组 lastResult  对应的 字典 lastWeightMap
   */
  let { lastResult: OrderByWeight, lastWeightMap: weightMap } = reorderbyWeight(
    selectedComps['data'],
    selectedComps
  );

  let LongestChild = longestChildArr_n2(
    getSlectedValueArr(lastSelectedCompsDir[timeKey], weightMap)
  );

  console.log(weightMap, OrderByWeight, LongestChild);

  TwoWayBind(selectedComps);

  ShortWay(
    lastSelectedCompsDir[timeKey],
    OrderByWeight,
    getSelectedValueArrName(LongestChild.longestdom[0]['name'].split(splitPart))
  );
}

/**
 * 装载 Selected Comps
 * @param {String} value -- id
 */
function renderSelectedComps(value) {
  //   console.log(value);

  let activeCompEl = document.getElementById('active_comps');
  let selectedComp_DomData = AssembleDomTree(value, 'remove');
  let domT = domTree(undefined, selectedComp_DomData);
  activeCompEl.appendChild(domT);
  selectedComps[value]['element'] = domT;

  //   console.log(addElement);
  //   element.parentNode.appendChild(addElement);
  //   let targetSelectedEl = document.getElementById(`selected_${value}`);
  endsTimeAnimation(domT, 'disnone', 0, 100);
  endsTimeAnimation(domT, 'rebackCompsAnimation');
  // settimeNth([0, 100], () => {
  //   targetSelectedEl.classList.remove('disnone');
  // });
}

/**
 * 批量 向 classname_ListEl 添加 监听事件
 * @param {String} className -- 类名
 * @param {String} type -- 绑定事件类型
 * @param {Function} handler -- 绑定 处理函数
 */
function massClassHandler(className, type, handler) {
  let classListEl = document.getElementsByClassName(className);
  for (let i = 0; i < classListEl.length; i++) {
    let element = classListEl[i];
    element.addEventListener(type, handler);
  }
}

/**
 *  <div class="uni_comp bunt_getme" value="ssss">
        <span class="comp_text" id="comp_text">ssss</span>
        <button class="comp_func_btn func_add_btn cursorPointer" id="add_btn">
          添加
        </button>
      </div>
 

let addCompTreeData = {
  queue: ['a_body'],
  a_body: {
    tag: 'div',
    props: ['classList'],
    attribute: ['value'],
    // events: ['click'],

    classList: ['uni_comp', 'bunt_getme'],
    value: ['ssss'],
    // click: addCompsH,

    queue: ['a_span', 'a_btn'],
    a_span: {
      tag: 'span',
      props: ['classList', 'id', 'innerHTML'],
      // attribute: ['value'],
      events: ['click'],
      innerHTML: 'ssss',
      id: 'comp_text',
      classList: ['comp_text'],
      // value: ['ssss'],
      // click: addCompsH,
    },
    a_btn: {
      tag: 'button',
      props: ['classList', 'id', 'innerHTML'],
      // attribute: ['value'],
      events: ['click'],
      innerHTML: '添加',
      id: 'add_btn',
      classList: ['comp_func_btn', 'func_add_btn', 'cursorPointer'],
      // value: ['ssss'],
      click: addCompsH,
    },
  },
};

<div class="uni_comp selected_comp bunt_getme" value="a367">
  <span class="comp_text" id="comp_text">
    a367
  </span>
  <button class="comp_func_btn func_remove_btn cursorPointer" id="remove_btn">
    移除
  </button>
</div>;

let removeCompTreeData = {
  queue: ['a_body'],
  a_body: {
    tag: 'div',
    props: ['classList'],
    attribute: ['value'],
    // events: ['click'],

    classList: ['uni_comp', 'selected_comp', 'bunt_getme'],
    value: ['a367'],
    // click: addCompsH,

    queue: ['a_span', 'a_btn'],
    a_span: {
      tag: 'span',
      props: ['classList', 'id', 'innerHTML'],
      // attribute: ['value'],
      events: ['click'],
      innerHTML: 'ssss',
      id: 'comp_text',
      classList: ['comp_text'],
      // value: ['ssss'],
      // click: addCompsH,
    },
    a_btn: {
      tag: 'button',
      props: ['classList', 'id', 'innerHTML'],
      // attribute: ['value'],
      events: ['click'],
      innerHTML: '移除',
      id: 'add_btn',
      classList: ['comp_func_btn', 'func_remove_btn', 'cursorPointer'],
      // value: ['ssss'],
      click: removeCompsH,
    },
  },
};
*/

/**
 * 组装 DomTree
 * @param {String} value 目标 唯一 ID
 * @param {String} AddorRemove "add" | "remove"
 * @returns
 */
function AssembleDomTree(value, AddorRemove) {
  let domTree;
  if (AddorRemove == 'add') {
    domTree = {
      queue: ['a_body'],
      a_body: {
        tag: 'div',
        props: ['classList', 'id'],
        attribute: ['value'],
        classList: ['uni_comp', 'bunt_getme'],
        id: `wait_${value}`,
        value: [value],

        queue: ['a_span', 'a_btn'],
        a_span: {
          tag: 'span',
          props: ['classList', 'id', 'innerHTML'],
          innerHTML: 'ssss',
          id: 'comp_text',
          classList: ['comp_text'],
        },
        a_btn: {
          tag: 'button',
          props: ['classList', 'id', 'innerHTML'],
          events: ['click'],
          innerHTML: '添加',
          id: 'add_btn',
          classList: ['comp_func_btn', 'func_add_btn', 'cursorPointer'],
          click: addCompsH,
        },
      },
    };
  }
  if (AddorRemove == 'remove') {
    domTree = {
      queue: ['r_body'],
      r_body: {
        tag: 'div',
        props: ['classList', 'id'],
        attribute: ['value'],
        classList: ['uni_comp', 'selected_comp', 'bunt_getme', 'disnone'],
        // classList: ['uni_comp', 'selected_comp', 'bunt_getme'],

        id: `selected_${value}`,

        value: [value],

        queue: ['r_span', 'r_btn'],
        r_span: {
          tag: 'span',
          props: ['classList', 'id', 'innerHTML'],
          innerHTML: value,
          id: 'comp_text',
          classList: ['comp_text'],
        },
        r_btn: {
          tag: 'button',
          props: ['classList', 'id', 'innerHTML'],
          events: ['click'],
          innerHTML: '移除',
          id: 'add_btn',
          classList: ['comp_func_btn', 'func_remove_btn', 'cursorPointer'],
          click: removeCompsH,
        },
      },
    };
  }
  return domTree;
}

function checkElementArrive(value) {
  let el = document.getElementById(`selected_${value}`);
  return el != undefined ? (el.nodeType == 1 ? true : false) : false;
}

function getSlectedValueArr(key, weightMap) {
  let a = [];
  console.log(key);
  for (let i = 0; i < key.length; i++) {
    a.push(weightMap[key[i]]);
  }
  console.log(a);
  return a;
}

function getSelectedValueArrName(weightarr) {
  let a = new Array(weightarr.length);
  let j;

  for (let i = 0; i < totalComps['data'].length; i++) {
    //全局 对应 weight 值
    // totalComps["data"][i]["weight"]
    j = weightarr.indexOf(totalComps[totalComps['data'][i]]['weight'] + '');
    if (j > -1) {
      a.splice(j, 1, totalComps['data'][i]);
    }
  }
  return a;
}

export {
  totalComps,
  massClassHandler,
  setStartSelectedComps,
  addCompsH,
  removeCompsH,
  reorderComps,
};
